//
//  EFSearchAddressViewController.m
//  EnjogFood
//
//  Created by 王芳 on 17/5/9.
//  Copyright © 2017年 wf. All rights reserved.
//

#import "EFSearchAddressViewController.h"
#import "EDJSearchAddressTextField.h"
#import "EFUserLocationItem.h"
#import "EFSearchAddressCell.h"

@interface EFSearchAddressViewController ()<UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource, BMKPoiSearchDelegate, BMKGeoCodeSearchDelegate, UIGestureRecognizerDelegate>
//@property (nonatomic, strong) UIView* citySelectView;
//@property (strong, nonatomic) UILabel *cityNameLabel;
@property (nonatomic, strong) EDJSearchAddressTextField *textField;
@property (nonatomic, copy) NSString* citySelectedName;
@property (nonatomic, copy) NSString* citySelectedId;

@property (nonatomic, strong) UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *poiArray;

@property (strong, nonatomic) BMKGeoCodeSearch * geoCodeSearch;
@property (strong, nonatomic) BMKPoiSearch    *bmkSeach;
@property (assign, nonatomic) NSInteger       pageIndex;
@property (copy, nonatomic)   NSString        *searchKey;


@property (nonatomic, assign) BOOL isInputted;
@end

@implementation EFSearchAddressViewController

- (instancetype)init{
    self = [super init];
    if (self) {
        self.bmkSeach = [[BMKPoiSearch alloc] init];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.pageIndex = 0;
    //self.bmkSeach = [[BMKPoiSearch alloc] init];
   // self.citySelectedName = @"北京";
    // Do any additional setup after loading the view.
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setImage:IMG(@"nav_icon_back") forState:UIControlStateNormal];
    [leftButton setImage:IMG(@"nav_icon_back") forState:UIControlStateHighlighted];
    [leftButton addTarget:self action:@selector(cancelTypeAddress)
         forControlEvents:UIControlEventTouchUpInside];
    [leftButton sizeToFit];
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton setTitle:@"取消" forState:UIControlStateNormal];
    [rightButton setTitleColor:kBlack333 forState:UIControlStateNormal];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [rightButton addTarget:self action:@selector(cancelTypeAddress)
          forControlEvents:UIControlEventTouchUpInside];
    rightButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
    [rightButton sizeToFit];
    rightButton.hidden = NO;
    
    self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.rightBarButtonItem= [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    
    UIView* titleView = [[UIView alloc] initWithFrame:ccr(44, 0, kScreenWidth - 113, 28)];
    titleView.backgroundColor = RGBCOLOR(0xF5F9F9);
//    [self.citySelectView addSubview:self.cityNameLabel];
//    UIImageView* arrowImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"content_icon_search_menu"]];
//    [self.citySelectView addSubview:arrowImgView];
//    
//    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onCitySelectViewTapped)];
//    [titleView addGestureRecognizer:tap];
//    
//    self.cityNameLabel.text = self.citySelectedName;
//    [self.cityNameLabel sizeToFit];
//    self.cityNameLabel.left = 6.8;
//    arrowImgView.left = self.cityNameLabel.right + 2;
//    self.cityNameLabel.top = (titleView.height - self.cityNameLabel.height)/2;
//    arrowImgView.top = (titleView.height - arrowImgView.height)/2;
//    [titleView addSubview:self.citySelectView];
    
    //add textField
    [titleView addSubview:self.textField];
    self.textField.left = 10;
    
    self.navigationItem.titleView = titleView;
    
    [self.view addSubview:self.tableView];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    // self.bmkSeach = [[BMKPoiSearch alloc] init];
    self.bmkSeach.delegate = self;
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    self.bmkSeach.delegate = nil;
    [self.textField resignFirstResponder];
}

- (void)cancelTypeAddress{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)onCitySelectViewTapped {
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark --Keyboard notification handler

- (void)keyboardWillShow:(NSNotification *) notification {
    self.textField.textAlignment = NSTextAlignmentLeft;
}

- (void)keyboardWillHide:(NSNotification *) notification {
    self.textField.textAlignment = NSTextAlignmentCenter;
}

#pragma mark --UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    // self.bmkSeach = [[BMKPoiSearch alloc] init];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([textField isFirstResponder]) {
        if ([[[textField textInputMode] primaryLanguage] isEqualToString:@"emoji"] || ![[textField textInputMode] primaryLanguage]) {
            NSLog(@"输入的是表情，返回NO");
            return NO;
        }
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        NSString *resultStr = [string stringByTrimmingCharactersInSet:set];
        if ([string length] && ![resultStr length]) {
            return NO;
        }
    }
    return YES;
}

- (void)textFieldValueChanged:(UITextField*)textField
{
    self.isInputted = YES;
    self.textField.textAlignment = NSTextAlignmentLeft;
    self.pageIndex = 0;
    [self poiRequest:textField.text pageIndex:0];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.textField resignFirstResponder];
    [self poiRequest:textField.text pageIndex:0];
    return YES;
}

#pragma mark -- map poi
- (void)poiRequest:(NSString *)key pageIndex:(NSInteger)page
{
    if (![self.searchKey isEqualToString:key]) {
        self.searchKey = key;
        if (key.length > 0) {
            self.pageIndex = page;
            [self poiSearchWithKey:key];
        } else {
            [self.poiArray removeAllObjects];
            [self.tableView reloadData];
        }
    }
}

- (BOOL)poiSearchWithKey:(NSString*)key
{
    [self addSearchLoadingIndicator];
    BMKCitySearchOption *citySearchOption = [[BMKCitySearchOption alloc]init];
    citySearchOption.pageIndex = (int)self.pageIndex;
    citySearchOption.pageCapacity = 10;
    if (self.citySelectedName == NULL || self.citySelectedName.length == 0) {
        citySearchOption.city = self.citySelectedName;
    }
    else if (APP_CONTEXT.locationManager.pinLocation && APP_CONTEXT.locationManager.pinLocation.cityName != nil && APP_CONTEXT.locationManager.pinLocation.cityName.length > 0) {
        citySearchOption.city= APP_CONTEXT.locationManager.pinLocation.cityName;
    }
    else {
        citySearchOption.city = @"北京";
    }
    citySearchOption.keyword = key;
    BOOL result = [self.bmkSeach poiSearchInCity:citySearchOption];
    return result;
}

#pragma mark --loading
- (void)addSearchLoadingIndicator
{
    self.textField.clearButtonMode = UITextFieldViewModeNever;
    self.textField.rightViewMode = UITextFieldViewModeAlways;
    UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    indicator.frame = ccr(-20, 0, 20, 20);
    indicator.backgroundColor = [UIColor clearColor];
    [indicator startAnimating];
    self.textField.rightView = indicator;
}

- (void)removeSearchLoadingIndicator
{
    self.textField.rightView = nil;
    self.textField.rightViewMode = UITextFieldViewModeNever;
    self.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
}

#pragma mark --UITableViewDelegate&UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.poiArray.count;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    EFSearchAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"address"];
    if (cell == NULL) {
        cell = [[EFSearchAddressCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"address"];
    }
    [cell setObject:self.poiArray[indexPath.row]];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //点击后，将地理位置传入
    EFUserLocationItem *locationItem = [self.poiArray  objectAtIndex:indexPath.row];
    APP_CONTEXT.locationManager.pinLocation = locationItem;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"selectLocationItem" object:locationItem];
    [self dismissViewControllerAnimated:YES completion:nil];
    if (self.delegate != nil && [self.delegate respondsToSelector:@selector(addressSelected:)]) {
        [self.delegate addressSelected:locationItem];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 77;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.textField resignFirstResponder];
}

//- (UILabel *)cityNameLabel {
//    if (!_cityNameLabel) {
//        _cityNameLabel = [[UILabel alloc] init];
//        _cityNameLabel.font = [UIFont systemFontOfSize:15];
//        _cityNameLabel.textColor = RGBCOLOR(0x333333);
//    }
//    return _cityNameLabel;
//}
//
//- (UIView *)citySelectView {
//    if (!_citySelectView) {
//        _citySelectView = [UIView new];
//    }
//    return _citySelectView;
//}

- (EDJSearchAddressTextField *)textField{
    if (!_textField) {
        _textField = [[EDJSearchAddressTextField alloc] initWithFrame:ccr(0, 0, 220, 28)];
        _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _textField.font = FONT(15.f);
        _textField.backgroundColor = RGBCOLOR(0xF5F9F9);
        _textField.textColor = RGBCOLOR(0x333333);
        //_textField.textAlignment = NSTextAlignmentCenter;
        _textField.returnKeyType = UIReturnKeySearch;
        _textField.borderStyle = UITextBorderStyleNone;
        _textField.layer.cornerRadius = 2.0;
        _textField.delegate = self;
        [_textField addTarget:self action:@selector(textFieldValueChanged:) forControlEvents:UIControlEventEditingChanged];
        
        UIImageView* iconView = [[UIImageView alloc] initWithImage:IMG(@"congtent_icon_search")];
        [iconView sizeToFit];
        _textField.leftView = iconView;
        _textField.leftViewMode = UITextFieldViewModeAlways;
        
    }
    return _textField;
}

- (NSMutableArray *)poiArray {
    if (!_poiArray) {
        _poiArray = [NSMutableArray array];
    }
    return _poiArray;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - kStatusBarHeight) style:UITableViewStylePlain];
         _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        
        UIView *topLine = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 0.5)];
        topLine.backgroundColor = RGBCOLOR(0xeeeeee);
        [_tableView addSubview:topLine];
        
        
    }
    return _tableView;
}

#pragma mark -
#pragma mark implement BMKSearchDelegate
- (void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult*)result errorCode:(BMKSearchErrorCode)error
{
    if (self.bmkSeach == searcher) {
        [self removeSearchLoadingIndicator];
        [self.HUD hide:NO];
        
        if (error == BMK_SEARCH_NO_ERROR) {
            if ([self isSearchKeyEmpty]) {
                return;
            }
            if (self.pageIndex == 0) {
                [self.poiArray removeAllObjects];
            }
            for (int i = 0; i < result.poiInfoList.count; i++) {
                BMKPoiInfo *info = [result.poiInfoList objectAtIndex:i];
                if (info.epoitype == 2 || info.epoitype == 4) {
                    continue;
                }
                [self.poiArray addObject:[EFUserLocationItem getUserLocation:info]];
            }
            [self.tableView reloadData];
            
        } else {
            [self.poiArray removeAllObjects];
            [self.tableView reloadData];
        }
    }
}

- (BOOL)isSearchKeyEmpty
{
    // DDLogDebug(@"search key is:%@", self.searchKey);
    return self.searchKey == nil || self.searchKey.length == 0;
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
